package com.google.code.p.restrpc.http;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author dz
 */
public class HttpClientException extends HttpException {
    
    private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
    
    private final HttpStatus httpStatus;
    
    private final byte[] responseBody;
    
    private final Charset responseCharset;
    
    public HttpClientException(HttpStatus httpStatus) {
        this(httpStatus, null, null);
    }
    
    public HttpClientException(HttpStatus httpStatus, byte[] responseBody) {
        this(httpStatus, responseBody, null);
    }
    
    public HttpClientException(HttpStatus httpStatus,
                               byte[] responseBody,
                               Charset responseCharset) {
        super(httpStatus.value() + " " + httpStatus.getDescription());
        this.httpStatus = httpStatus;
        this.responseBody = responseBody != null ? responseBody : new byte[0];
        this.responseCharset = responseCharset != null ? responseCharset
                                                      : DEFAULT_CHARSET;
    }
    
    /**
     * Returns the HTTP status code.
     */
    public HttpStatus getHttpStatus() {
        return this.httpStatus;
    }
    
    /**
     * Returns the HTTP status code.
     */
    public int getStatusCode() {
        return this.httpStatus.value();
    }
    
    /**
     * Returns the HTTP status text.
     */
    public String getStatusText() {
        return this.httpStatus.getDescription();
    }
    
    /**
     * Returns the response body as a byte array.
     * 
     * @since 3.0.5
     */
    public byte[] getResponseBodyAsByteArray() {
        return responseBody;
    }
    
    /**
     * Returns the response body as a string.
     * 
     * @since 3.0.5
     */
    public String getResponseBodyAsString() {
        try {
            return new String(responseBody, responseCharset.name());
        }
        catch (UnsupportedEncodingException ex) {
            // should not occur
            throw new InternalError(ex.getMessage());
        }
    }
}
